#include "lvgl.h"
#include "examples/lv_examples.h"
#include "lvgl_control.hpp"

#include "spi_lcd.hpp"  // 假设你已经实现了 SPI 屏幕驱动

LVGLControl::LVGLControl() = default;

void LVGLControl::init() {
    
    _spi_lcd_init();

    // 初始化 LVGL
    lv_init();

    // 初始化显示和输入设备
    initDisplay();
}

void LVGLControl::initDisplay() {
    static lv_color16_t draw_buf1[160 * 80];
    static lv_color16_t draw_buf2[160 * 80];
    lv_display_t* disp_drv = lv_display_create(160, 80);
    lv_display_set_buffers(disp_drv, &draw_buf1, &draw_buf2, sizeof(draw_buf1), LV_DISPLAY_RENDER_MODE_DIRECT);
    lv_display_set_flush_cb(disp_drv, LCDDisplay::lcdDisplayFlushcb);
}

void LVGLControl::showHelloWorld() {
    /*Change the active screen's background color*/
    lv_obj_set_style_bg_color(lv_screen_active(), lv_color_hex(0x003a57), LV_PART_MAIN);

    /*Create a white label, set its text and align it to the center*/
    lv_obj_t * label = lv_label_create(lv_screen_active());
    lv_label_set_text(label, "Hello world");
    lv_obj_set_style_text_color(lv_screen_active(), lv_color_hex(0xffffff), LV_PART_MAIN);
    lv_obj_align(label, LV_ALIGN_CENTER, 0, 0);
}

void LVGLControl::showNumInit() {
    lv_obj_set_style_bg_color(lv_screen_active(), lv_color_hex(0x003a57), LV_PART_MAIN);

    /*Create a white label, set its text and align it to the center*/
    label = lv_label_create(lv_screen_active());
    lv_label_set_text(label, "Value:");
    lv_obj_align(label, LV_ALIGN_CENTER, 0, 0);
}

void LVGLControl::showNumInner(uint32_t value) {
    lv_label_set_text_fmt(label, "Value:%d", value);
}



void LVGLControl::showExample() {
    lv_example_anim_2();
}

void LVGLControl::_spi_lcd_init()
{
    const SPI spiObj(SPI2_HOST,
                   SPI_CLK_GPIO_PIN,
                   SPI_MOSI_GPIO_PIN,
                   SPI_MISO_GPIO_PIN);

    spiObj.init();
    LCDDisplay lcdObj(SPI2_HOST, LCD_NUM_WR, LCD_NUM_CS, LCD_NUM_BL, LCD_NUM_RST);
    lcdObj.init();
    lcdObj.setSPIInterface(spiObj);
}

void LVGLControl::lcdOn() {
    this->lcdObj.lcdOn();
}

void LVGLControl::lcdClose() {
    this->lcdObj.lcd_off();
}

void LVGLControl::lvglLcdClean(uint16_t color) {
    this->lcdObj.lcdClear(color);
}